"""
IO多路复用select 实现多客户端通信

1 将关注的IO放入对应的监控类别列表
2 通过select函数进行监控
3 遍历select返回值列表，确定就绪IO事件
4 处理发生的IO事件
"""

from socket import *
from select import select

s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind('0.0.0.0', 8888)
s.listen(5)

# 设置关注的IO
rlist = [s]
wlist = []
xlist = []

while True:
    # 监控IO的发生
    rs, ws, xs = select(rlist, wlist, xlist)
    # 遍历三个返回值列表，判断哪个IO发生
    for r in rs:
        # 如果套接字就绪则处理链接
        if r is s:
            c, addr = r.accept()
            print('Connect from', addr)
            # 加入新的关注IO
            rlist.append(c)
        else:
            data = r.recv(1024)
            if not data:
                rlist.remove(r)
                r.close()
                continue
            print(data.decode())
            # r.send(b'OK')
            # 希望我们主动处理这个IO
            wlist.append(r)

    for w in ws:
        w.send(b'Ok,Thanks')
        wlist.remove(w)

    for x in xs:
        pass
